package com.li.o2oSystem.util.weixin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.li.o2oSystem.dto.UserAccessToken;
import com.li.o2oSystem.dto.WechatUser;
import com.li.o2oSystem.entity.PersonInfo;

/**
 * 微信工具类
 * @author Administrator
 *
 */
public class WechatUtil {
	private static Logger log = LoggerFactory.getLogger(WechatUtil.class);
	/**
	 * 获取UserAccessToken实体类 
	 * @param code
	 * @return
	 * @throws IOException
	 */
	public static UserAccessToken getUserAccessToken(String code) throws IOException{
		//微信测试号里的appId
		String appId = "wx1f8783ad7c3873b1";
		//测试号信息里的appsecret79226250c98fb10e867abc8d8c04756b
		String appsecret = "79226250c98fb10e867abc8d8c04756b";
		//根据传入的code，拼接出访问微信定义的接口的url
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
		//向相应的url发送请求获取token json字符串
		String tokenStr = httpsRequest(url,"GET",null);
		log.debug("请求获取的token信息："+tokenStr);
		UserAccessToken token = new UserAccessToken();
		ObjectMapper objectMapper = new ObjectMapper();
		try{
			//将json字符串转换成相应对象
			token = objectMapper.readValue(tokenStr, UserAccessToken.class);
		log.debug("token转化为对象："+token);
		}catch(Exception e){
			e.printStackTrace();
		}
		if(token == null){
			return null;
		}
		return token;
	}
	/**
	 * 获取WechatUser实体类
	 * @param accessToken
	 * @param openId
	 * @return
	 */
	public static WechatUser getUserInfo(String accessToken,String openId){
		//根据传入的accessToken以及openId拼接出访问微信定义的端口并获取用户信息的url
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openId"+openId+"&lang=zh_CH";
		//访问该url,获取用户信息字符串
		String userStr = httpsRequest(url,"GET",null);
		WechatUser user = new WechatUser();
		ObjectMapper  objectMapper = new ObjectMapper();
		try{
			//将json字符串转换成相应的对象
			user = objectMapper.readValue(userStr, WechatUser.class);
		}catch(Exception e){
			e.printStackTrace();
		}
		if(user == null){
			return null;
		}
		return user;
	}
	/**
	 * 发起https请求，并获取结果
	 * @param requestUrl	请求地址
	 * @param RequestMethod		请求方法
	 * @param outputStr	提交的数据
	 * @return json字符串
	 */
	private static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		StringBuffer buffer = new StringBuffer();
		try{
			//创建SSLcontext对象，并使我们指定的信任管理器初始化
			TrustManager[] tm = {new MyX509TurstManager()};
			SSLContext sslContext = SSLContext.getInstance("SSL","SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			//从上述SSLContext对象中得到SSLSocketFactory对象;
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			
			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			
			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setRequestMethod(requestMethod);//设置请求方法
			
			if("GET".equalsIgnoreCase(requestMethod)){
				httpUrlConn.connect();
			}
			
			//当有数据需要提交时
			if(null != outputStr){
				OutputStream outputStream = httpUrlConn.getOutputStream();
				//注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			
			//将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
			BufferedReader  bufferedReader = new BufferedReader(inputStreamReader);
			
			String str = null;
			while((str = bufferedReader.readLine()) != null){
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
		}catch(Exception e){
			e.printStackTrace();
		}
		return buffer.toString();
	}
	/**
	 * 将WechatUser里的信息转换成PersonInfo的信息并返回PersonInfo实体类
	 * 
	 * @param user
	 * @return
	 */
	public static PersonInfo getPersonInfoFromRequest(WechatUser user) {
		PersonInfo personInfo = new PersonInfo();
		personInfo.setName(user.getNickName());
		personInfo.setGender(user.getSex() + "");
		personInfo.setProfileImg(user.getHeadimgurl());
		personInfo.setEnableStatus(1);
		return personInfo;
	}
}
